import { urlAccessible } from "./urlAccessible";

export class RedirectStopper {
  enable: boolean = true;
  banList: string[] = [];
  contentLoaded: boolean = false;
  firstLocation: string = "";
  constructor() {
    this.stopRedirect();
  }
  public setEnable(status: boolean) {
    this.enable = status;

    this.contentLoaded = true;
    // _console.log(this.firstLocation, "first", status);
    if (this.firstLocation != "" && !status) {
      location.href = this.firstLocation;
      this.firstLocation = "";
    }
  }
  public setBanList(list: string[]) {
    this.banList = list;
  }
  private stopRedirect() {
    window.navigation.addEventListener("navigate", (e) => {
      if (e.navigationType === "replace") {
        return;
      }
      if (!this.contentLoaded) {
        e.preventDefault();
        this.firstLocation = e.destination.url;
        return;
      }
      const res =
        this.enable && !urlAccessible(this.banList, e.destination.url);

      if (res) {
        // _console.log(res, e.destination.url);
        e.preventDefault();
      }
    });
  }
}
